package com.hf.fetch

import com.hf.constant.OrderLunchConst
import com.hf.date.DateUtils
import com.hf.mail.AbstractMailService
import com.hf.mail.MailMessage
import com.hf.mail.MailSenderService
import com.hf.order.UserOrderHistoryService
import com.hf.security.OrderUser
import com.hf.security.SystemConfigService
import com.hf.template.GspTemplateUtils

class MailFetchService extends AbstractMailService {

	UserOrderHistoryService userOrderHistoryService
	UserFetchSummaryService userFetchSummaryService
	SystemConfigService systemConfigService

	void sendMail() {
		List<OrderUser> orderedUserList = userOrderHistoryService.getOrderedUserListToay()
		if (orderedUserList?.empty) {
			sendNoOrderMail()
		} else {
			int fetchPersonNumber = userFetchSummaryService.getFetchPersonNumber(orderedUserList.size())
			List<UserFetchSummary> orderedUserFetchSummaryList = userFetchSummaryService.getUserFetchSummarySortList(orderedUserList)
			List<UserFetchSummary> fetchUserList = userFetchSummaryService.getUserFetchSummaryFinalList(orderedUserFetchSummaryList, fetchPersonNumber)
			log.info "今天$orderedUserList.size 人订餐, 取餐人: " + fetchUserList

			if (OrderLunchConst.IS_TEST) {
				//
			} else {
				userFetchSummaryService.updateOrderAndFetchCount(orderedUserList, fetchUserList)
			}
			send(orderedUserList, orderedUserFetchSummaryList, fetchUserList)
		}
	}

	private void send(List<OrderUser> orderedUserList, List<UserFetchSummary> orderedUserFetchSummaryList, List<UserFetchSummary> fetchUserSummaryList) {
		MailMessage mail = new MailMessage()

		List<String> fetcherNameList = fetchUserSummaryList.collect { UserFetchSummary userFetchSummary ->
			userFetchSummary.user.name
		}
		mail.subject = OrderLunchConst.FROM_ORDER_LUNCH + "Today Fetcher: $fetcherNameList  " + DateUtils.todayInfo

		if(OrderLunchConst.IS_TEST) {
			mail.to << OrderLunchConst.ADMIN_EMAIL
		} else {
			orderedUserList.each { OrderUser user ->
				mail.to << user.email
			}

			fetchUserSummaryList.each { UserFetchSummary userFetchSummary ->
				mail.Cc << userFetchSummary.user.email
			}
		}

		boolean isRainDay = systemConfigService.isRainDay
		String fetchHtml = GspTemplateUtils.renderTemplate('/fetch/emailFetchList', [fetchUserSummaryList: orderedUserFetchSummaryList])

		mail.htmlText = GspTemplateUtils.renderTemplate('/fetch/emailFetchLunch',[orderCount : orderedUserList.size(), fetcherNameList : fetcherNameList, isRainDay: isRainDay, fetchHtml: fetchHtml])

		mailSenderService.sendAsyn(mail)
	}

	void sendNoOrderMail() {
		MailMessage mail = new MailMessage()
		mail.subject = "No order person  " + DateUtils.todayInfo

		mail.to << OrderLunchConst.ADMIN_EMAIL

		mail.plainText = 'No order person'

		mailSenderService.sendAsyn(mail)
	}
}
